package com.capgemini.simpleappblanche.helper.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;

import com.capgemini.simpleappblanche.domain.constant.RoleConstant;
import com.capgemini.simpleappblanche.domain.security.Role;
import com.capgemini.simpleappblanche.domain.security.User;

public final class UserHelper {

    
    /**
     * check if logged user is admin
     * @param auth auth
     * @return true is ADMIN
     */
    public static boolean isAdmin(Authentication auth){
        
        boolean result = false;
        
        if(auth != null){
            User user = (User)auth.getPrincipal();
            
            if(AuthorityUtils.authorityListToSet(user.getRoles()).contains(RoleConstant.ROLE_ADMIN)){
                result = true;
            }
        }
        
        return result;
    }

    /**
     * get agency id from User Role/permission
     * @param permissionToSearch permission to search in User's permissions
     * @return list of id
     */
    public static List<Long> getAgencyIdsByPermission(Authentication auth, String permissionToSearch) {
        List<Long> agencyIds = new ArrayList<Long>();
        
        
        if(auth != null){
            User user = (User)auth.getPrincipal();
            
            //for each role of User
            for(Role role : user.getRoles()){
                
                //some role has not agency
                if(role.getAgency() != null){
                
                    //check if role's Permission contain the searched one
                    if(AuthorityUtils.authorityListToSet(role.getPermissions()).contains(permissionToSearch)){
                        
                        //role contains the searched permission, add agency id
                        if(agencyIds.contains(role.getAgency().getId())){
                            agencyIds.add(role.getAgency().getId());
                        }
                    }
                }
            }
        }
        
        
        return agencyIds;
    }
}
